<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<?sjs
//
// Admin page of the atom-anno sample implementation
//
// Author: Alan Green (alangreen@google.com)
//
pow_include('db.sjslib');
pow_include('service.sjslib');
aaInitDb();
?>
<?sjs
var pageMessage = '';

// Adds a new user
function addUser(name, fullName) {
  // Hmmm. not using SQL placeholders. I don't like that.
  var result = DB.exec("INSERT INTO user(name, fullName) "
      + "VALUES('" + name + "', '" + fullName + "')");
  if (result) {
    pageMessage = "Added user " + name + ".";
  } else {
    pageMessage = "User with that name already exists";
  }
  aaResetRewriteRules();
}


// Recreates the database
function recreateDatabase() {
  dbDrop();
  dbCreateSchema();
  pageMessage = "Recreated database. Users wiped."
}


// Removes a user
function removeUser(name) {
  var result = DB.exec("DELETE FROM user WHERE name = '" + name + "'");
  if (result) {
    pageMessage = "Removed user " + name + ".";
  } else {
    pageMessage = "Error. Could not remove user " + name + ".";
  }
  aaResetRewriteRules();
}


// Updates a user
function updateUser(name, fullName) {
  var result = DB.exec("UPDATE user SET fullName = '" + fullName 
      + "' WHERE name = '" + name + "'");
  if (result) {
    pageMessage = "Updated user " + name + ".";
  } else {
    pageMessage = "Error. Could not update user " + name + ".";
  }
}


// Work out what action was executed, if any
var action = aaGetPostParameter('action');
var name = aaGetPostParameter('name1');
var fullName = aaGetPostParameter('name2');
if (action) {
  switch(action) {
    case 'add':
      addUser(name, fullName);
      break;
    case 'recreatedb':
      recreateDatabase();
      break;
    case 'remove':
      removeUser(name);
      break;
    case 'update':
      updateUser(name, fullName);
      break;
    default:
      pageMessage = 'Unknown action: ' + action;
  }
}

// Write out value of pageMessage variable.
document.writeln("<script type='text/javascript'>");
document.writeln("var pageMessage='" + pageMessage + "';");
document.writeln("</script>");

?>
<html>
<head>
  <title>Atom Anno Server Admin</title>
  <link rel="stylesheet" href="style.css" type="text/css" />

<script type="text/javascript">

/* Library functions. */
function strip(s) {
  return s.replace(/^\s*\s/, "").replace(/\s*$/, "");
}

/* Submit an action */
function submitAction(actionType, name1, name2) {
  document.getElementById('param-type').value = actionType;
  document.getElementById('param-name1').value = name1 || '';
  document.getElementById('param-name2').value = name2 || '';
  document.getElementById('action-form').submit();
}


/* Handle recreating the database */
function recreateDatabasePressed() {
  var ok = confirm('Delete and re-create the database?');
  if (!ok) return;
  ok = confirm('Are you really sure? This will destroy all existing data.');
  if (!ok) return;
  ok = confirm('Press OK one more time to wipe the database.');
  if (!ok) return;
  submitAction('recreatedb');
}


/* Checks a full name for compliance with the rules. */
function checkFullName(fullName) {
  if (!fullName.match(/^[A-Za-z ]+$/)) {
    alert('Full name must not be empty, and must consist of letters and '
        + 'spaces only.');
    return false;
  }
  return true;
}


/* Handle adding a user. */
function addUserPressed() {
  var name = strip(document.getElementById('add-user-name').value);
  if (!name) {
    alert('Name must not be empty.');
    return;
  }
  if (!name.match(/^[a-z][a-z0-9]*$/)) {
    alert('Name must start with a lower-case letter, and consist of numbers, '
        + 'digits, and dashes ("-") only.');
    return;
  }
  if (name == 'admin') {
    alert('Name must not be "admin".');
    return;
  }

  var fullName = strip(document.getElementById('add-user-full-name').value);
  if (!checkFullName(fullName)) {
    return;
  }

  submitAction('add', name, fullName);
}


/* Handles removing a user. */
function removeUserPressed(name) {
  var ok = confirm('Go ahead and remove user ' + name + ', including all data'
      + ' stored for ' + name + '?');
  if (!ok) {
    return;
  }
  ok = confirm('Are you really sure? If you press OK, then ' + name + ' will '
      + ' be deleted.');
  if (!ok) {
    return;
  }

  submitAction('remove', name);
}


/* Handles updating a user's name. */
function updateUserPressed(name) {
  var elementId = 'update-user-fullname-' + name
  var fullName = strip(document.getElementById(elementId).value);
  if (!checkFullName(fullName)) {
    return;
  }

  submitAction('update', name, fullName);
}


/** Called to initialise page when finished loading. */
function pageLoaded() {
  if (pageMessage) {
    var messageDiv = document.getElementById('page-message');
    messageDiv.innerHTML = pageMessage;
    messageDiv.className = 'aa-message';
  }
}
window.onload = pageLoaded;

</script>
</head>
<body>
  <h1>Atom Anno Server Administration</h1>

  <div id="page-message"></div>

  <h2>Database</h2>
  <button onClick="recreateDatabasePressed();">Recreate Database</button>

  <h2>Users</h2>
  <?sjs
  {
    var rows = DB.exec("SELECT name, fullName FROM user ORDER BY name");
    if (rows.length) {
      document.write('<table><tr><th>Name</th><th>Feed</th>');
      document.writeln('<th>Full Name</th><th>&nbsp;</th></tr>');
      for (var i = 0 ; i < rows.length; i++) {
        var name = rows[i][0];
        var fullName = rows[i][1];
        document.write('<tr><td>' + name + '</td><td>');
        var uri = aaCalculateFeedUri(name);
        document.write('<a href="' + uri + '">' + uri + '</a></td><td>');
        document.write('<input id="update-user-fullname-' + name 
            + '" type="text" value="' + fullName + '" /></td><td>');
        document.write('<button onclick="updateUserPressed(\'' + name);
        document.write('\');">Update Full Name</button> ');
        document.write('<button onclick="removeUserPressed(\'' + name);
        document.write('\');">Remove</button></td>');
        document.writeln('</tr>');
      }
      document.writeln('</table>');
    } else {
      document.writeln('<p>No users in database.</p>');
    }
  }
  ?>

  <p id="add_user">
    <label for="add-user-name">Username (id)</label><br />
    <input id="add-user-name" type="text" /><br />
    <label for="add-user-full-name">Full name</label><br />
    <input id="add-user-full-name" type="text" /><br />
    <button onClick="addUserPressed();">Add user</button>
  </p>

  <form id="action-form" class="aa-hidden" method="post">
    <input id="param-name1" name="name1" type="hidden" /> 
    <input id="param-name2" name="name2" type="hidden" /> 
    <input id="param-type" name="action" type="hidden" /> 
  </form>
</body>
</html>
